package cn.poem.exception;

import cn.poem.base.Response;
import cn.poem.base.ResponseCode;
import cn.poem.base.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 全局异常
 * @Author sugar
 * @Date 2021/5/12 5:26 PM
 * @Version 1.0
 */
@ControllerAdvice
public class GlobalExceptionHander {
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHander.class);
    /**
     * 系统异常处理
     *
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseData<Object> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            /**
             * 404异常
             */
            return Response.fail(e.getMessage(), ResponseCode.NOT_FOUND_CODE);
        } else {
            LOGGER.error("异常", e);
            return Response.fail(e.getMessage(), ResponseCode.SERVER_ERROR_CODE);
        }
    }

    /**
     * 自定义异常处理
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = PoemException.class)
    @ResponseBody
    public ResponseData<Object> customerErrorHandler(HttpServletRequest request, PoemException e) throws Exception {
        return Response.fail(e.getMessage(), e.getCode());

    }


}
